package shutdowner;

import java.io.IOException;



public class ShutdownThread extends Thread {
	
	int SecondsBeforeShutdown = 1000;
	
	boolean isRunning = false;
	
	public ShutdownThread(int NewTimeout) {
		SecondsBeforeShutdown = NewTimeout;
		isRunning = false;
	}
	
	
	public synchronized void setNewTimeout(int NewTimeout) {
		SecondsBeforeShutdown = NewTimeout;
	}
	
	public synchronized void startCountdown() {
		isRunning = true;
	}
	
	public synchronized void stopCountdown() {
		isRunning = false;
	}
	
	public boolean isRunning() {
		return isRunning;
	}
	
	public void run() {
		boolean stopnow = false;
		// for exiting cleanly
		while (!stopnow) {
			// if countdown is active, count down the seconds
			if (isRunning) {
				SecondsBeforeShutdown = SecondsBeforeShutdown - 1;
				MainWindow.displayNewTimeOut(SecondsBeforeShutdown);
				
				// if end of time reached shutdown system
				if (SecondsBeforeShutdown <= 0) {
					Runtime runtime = Runtime.getRuntime();
					try {
						runtime.exec("shutdown -s");
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						stopnow = true;
						MainWindow.closeAll();
					}
				}
			}
			
			try {
				ShutdownThread.sleep(1000);
			} catch (InterruptedException e) {
				stopnow = true;
			}
		}
	}

}
